const commentModel = require("../models/commentModel");
const userModel = require("../models/userModel");

const addComment = async ({ user_id, md_id, content }) => {
  try {
    await new commentModel({
      user_id: Number(user_id),
      md_id: Number(md_id),
      content,
    }).save();
  } catch (err) {
    throw new Error(err);
  }
};

const getComment = async ({ user_id, md_id }) => {
  try {
    const comments = await commentModel.find({
      user_id: parseInt(user_id),
      md_id: parseInt(md_id),
    });
    const list = [];
    for (const item of comments) {
      const user = await userModel.findOne({ user_id: item.user_id });
      list.push({
        ...item._doc,
        user: user._doc,
      });
    }
    return list;
  } catch (err) {
    console.error(err);
    throw new Error(err);
  }
};

module.exports = {
  addComment,
  getComment,
};
